﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using WorkOrder.Business;
using System.Data;
using System.Text;

namespace WorkOrder
{
    public partial class queryExcept : System.Web.UI.Page
    {
        Business_Table_Work_order B_T_w = new Business_Table_Work_order();
        static DataTable dt;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] == null || Session["UserID"].ToString() == "")
            {
                Session.Clear();
                ClientScript.RegisterClientScriptBlock(this.GetType(), "windowhref", "<script type='text/javascript'>alert('对不起，您还没有登录系统！');window.parent.location.href='../login.aspx';</script>");
            }
            if (!Page.IsPostBack)
            {
                ddlExceptType.Items.Clear();
                ddlExceptType.DataTextField = "exception_type";
                ddlExceptType.DataValueField = "exception_type_id";
                ddlExceptType.DataSource = new Business_Table_Exception().GetExceptType();
                ddlExceptType.DataBind();
                ddlExceptType.Items.Add(new ListItem("-- 请选择 --", "0"));
                ddlExceptType.SelectedIndex = ddlExceptType.Items.Count - 1;

                GridView1.Attributes.Add("SortExpression", "task_time");
                GridView1.Attributes.Add("SortDirection", "DESC");
                txtRow.Text = GridView1.PageSize.ToString();

                dt = null;
            }
        }

        
        #region 查询按钮事件
        protected void btnSearch_ServerClick(object sender, EventArgs e)
        {
            BindGridView();
        }
        #endregion

        private void BindGridView()
        {
            if (txtSTART_DATE.Value.Trim() == "" || txtEND_DATE.Value.Trim() == "")
            {
                lblMsg.Text = "提示信息：请输入起始时间和结束时间！";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "windhref", "<script type='text/javascript'>alert('提示信息：请输入起始时间和结束时间！');</script>");
                return;
            }
            string sqlstr = " 1=1 and create_time between '" + txtSTART_DATE.Value.Trim() + " 0:0:0' and '" + txtEND_DATE.Value.Trim() + " 23:59:59'";
            if (ddlExceptType.SelectedValue != "0")
                sqlstr += " and A.exception_type_id=" + ddlExceptType.SelectedValue;

            lblMsg.Text = "";
            dt = B_T_w.GetExceptionOrder(sqlstr).Tables[0];

            if (dt != null)
                hidRowCount.Value = dt.Rows.Count.ToString();
            lblRowCount.Text = "共&nbsp;" + hidRowCount.Value + "&nbsp;条记录";

            try { GridView1.PageSize = Convert.ToInt32(txtRow.Text.Trim()); }
            catch { }

            // 获取GridView排序数据列及排序方向
            string sortExpression = this.GridView1.Attributes["SortExpression"];
            string sortDirection = this.GridView1.Attributes["SortDirection"];

            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
            {
                if (dt != null)
                    dt.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
            }

            // GridView绑定并显示数据
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        #region 处理光标行颜色事件
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex >= 0)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor,this.style.background='#ffe3a0'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                if (e.Row.Cells[6].Text.Length > 25)
                    e.Row.Cells[6].Text = e.Row.Cells[6].Text.Substring(0, 25) + "......";
            }
        }
        #endregion

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                GridView1.PageIndex = e.NewPageIndex;
                BindGridView();
                TextBox tb = (TextBox)GridView1.BottomPagerRow.FindControl("inPageNum"); tb.Text = (GridView1.PageIndex + 1).ToString();
            }
            catch { }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "go")
            {
                try
                {
                    TextBox tb = (TextBox)GridView1.BottomPagerRow.FindControl("inPageNum");
                    int num = Int32.Parse(tb.Text);
                    GridViewPageEventArgs ea = new GridViewPageEventArgs(num - 1);
                    GridView1_PageIndexChanging(null, ea);
                }
                catch
                { }
            }
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();

            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";

            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == this.GridView1.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }

            // 重新设定GridView排序数据列及排序方向
            GridView1.Attributes["SortExpression"] = sortExpression;
            GridView1.Attributes["SortDirection"] = sortDirection;

            BindGridView();
        }

        #region 导出到excel文件
        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            if (dt != null)
            {
                string[] title = { "工单号", "工单主题", "区域", "镇区", "问题类型", "问题描述", "签收人" };
                string[] field = { "order_number", "title", "area_name", "town_name", "exception_type", "exception", "name_remark" };
                ExportDsToXls(this.Page, "查询工单问题", title, field, dt);
            }
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            if (dt != null)
            {
                string[] title = { "工单号", "工单主题", "区域", "镇区", "问题类型", "问题描述", "签收人" };
                string[] field = { "order_number", "title", "area_name", "town_name", "exception_type", "exception", "name_remark" };
                ExportDsToXls(this.Page, "查询工单问题", title, field, dt);
            }
        }

        public static string ExportTable(string[] title, string[] field, DataTable table)
        {
            StringBuilder sb = new StringBuilder();

            //列名
            string tmp = "";
            for (int i = 0; i < title.Length; i++)
            {
                if (i > 0) tmp += "\t";
                tmp += title[i];
            }
            sb.AppendLine(tmp);
            tmp = null; title = null;

            //数据内容
            foreach (DataRow row in table.Rows)
            {
                string str = "";

                for (int j = 0; j < field.Length; j++)
                    foreach (DataColumn column in table.Columns)
                    {
                        if (column.ColumnName == field[j])
                        {
                            if (j > 0)
                                str += "\t";
                            if (DBNull.Value.Equals(row[column]))
                                str += "";
                            else if (row[column].ToString() == "False")
                                str += "否";
                            else if (row[column].ToString() == "True")
                                str += "是";
                            else str += row[column].ToString().Replace("\r", " ").Replace("\n", " ");
                        }
                    }
                sb.AppendLine(str);
                str = null;
            }
            field = null;

            return sb.ToString();
        }

        public static void ExportDsToXls(Page page, string fileName, string[] title, string[] field, DataTable table)
        {
            page.Response.Clear();
            page.Response.Buffer = true;
            page.Response.Charset = "GB2312";
            //page.Response.Charset = "UTF-8";
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + System.DateTime.Now.ToString("_yyyyMMddHHmmss") + ".xls");
            page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
            page.Response.ContentType = "application/vnd.ms-excel";//设置输出文件类型为excel文件。 
            page.EnableViewState = false;
            page.Response.Write(ExportTable(title, field, table));
            page.Response.End();
        }
        #endregion
    }
}
